﻿namespace Pap.Web.Modules.Membership.Views
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Coolite.Ext.Web;
    using global::Utils.UIPermission;
    using Pap.Data;
    using Pap.Web.Modules.Membership.ViewModel;
    using Pap.Web.Utils;

    /// <summary>
    /// Role Details Form
    /// </summary>
    public partial class RoleDetails : BasePage<RoleDetailsViewModel>, IPermittedPage
    {

        #region [ Variables ]

        /// <summary>
        /// 
        /// </summary>
        IRole _Role;
        /// <summary>
        /// 
        /// </summary>
        List<Guid> _Permissions;

        #endregion

        #region [ Query Strings ]

        /// <summary>
        /// Gets the editing role ID.
        /// </summary>
        public string EditingRoleID
        {
            get
            {
                return Request.QueryString["RoleID"];
            }
        }

        #endregion

        #region [ Fill Controls ]

        /// <summary>
        /// Fills the controls.
        /// </summary>
        /// <param name="_Role">The _ role.</param>
        private void FillControls(IRole _Role)
        {
            txtRoleName.Text = _Role.RoleName;
        }

        /// <summary>
        /// Fills the permissions.
        /// </summary>
        private void FillPermissions()
        {
            this.lstPermissions.DataSource = this.ViewModel.GetAllPermissions();
            this.lstPermissions.DataBind();
        }

        #endregion

        #region [ Events ]

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// ?
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.ViewModel != null)
            {
                if (!Ext.IsAjaxRequest)
                {
                    if (!Page.IsPostBack)
                    {
                        if (!string.IsNullOrEmpty(this.EditingRoleID))
                        {
                            this._Role = this.ViewModel.GetRoleByID(EditingRoleID.ToGuid());
                            //------------------------------------------------------
                            MainForm.Title = string.Format("{0} ({1})", GetLocalResourceObject("TitleEditRole").ToString(), _Role.RoleName);

                            FillControls(_Role);
                            this.lstPermissions.ItemDataBound += new DataListItemEventHandler(this.lstPermissions_ItemDataBound);
                        }
                        FillPermissions();
                    }
                }
            }
        }

        /// <summary>
        /// Handles the ItemDataBound event of the lstPermissions control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.DataListItemEventArgs"/> instance containing the event data.</param>
        protected void lstPermissions_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.DataItem != null)
            {
                var permission = e.Item.DataItem as IPermission;
                if (permission != null)
                {
                    var checkBox = e.Item.FindControl("chkSelect") as Checkbox;
                    //---------------------------------------------------------
                    checkBox.Checked = this._Role.Permissions.Any(p => p.PermissionID == permission.PermissionID);
                }
            }
        }

        /// <summary>
        /// Handles the Clicked event of the btnSubmit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnSubmit_Clicked(object sender, AjaxEventArgs e)
        {
            this.Validate();
            if (this.IsValid)
            {
                try
                {
                    FormStatusBar.ShowBusy(GetLocalResourceObject("MSGWorking").ToString());
                    if (!string.IsNullOrEmpty(EditingRoleID))
                    {
                        Guid roleID = EditingRoleID.ToGuid();
                        List<Guid> permissions = GetCheckedPermissions();
                        this.ViewModel.UpdateRole(roleID, txtRoleName.Text, permissions);
                        //--------------------------------------------------------------
                        //Ext.Redirect("~/Membership/RolesList", GetLocalResourceObject("MSGRedirecting").ToString());
                        this.Redirect("RolesList");
                    }
                    else
                    {
                        List<Guid> permissions = GetCheckedPermissions();
                        this.ViewModel.CreateNewRole(txtRoleName.Text, permissions);
                        //--------------------------------------------------------------
                        ClearControls();
                    }
                    FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = GetLocalResourceObject("MBDoneText").ToString(), IconCls = "", Clear2 = true });
                }
                catch
                {
                    FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = GetLocalResourceObject("MBCantSave").ToString(), IconCls = "", Clear2 = true });
                }
            }
            else
            {
                FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = GetLocalResourceObject("MBFormInvalid").ToString(), IconCls = "", Clear2 = true });
            }
        }

        /// <summary>
        /// Handles the Clicked event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnCancel_Clicked(object sender, AjaxEventArgs e)
        {
            //Ext.Redirect("~/Membership/RolesList", GetLocalResourceObject("MSGRedirecting").ToString());
            this.Redirect("RolesList");
        }

        /// <summary>
        /// Handles the Validate event of the txtRoleName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void txtRoleName_Validate(object sender, ServerValidateEventArgs e)
        {
            if (!ValidateRoleName())
            {
                e.IsValid = false;
            }
        }

        /// <summary>
        /// Handles the Validate event of the lstPermissions control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void lstPermissions_Validate(object sender, ServerValidateEventArgs e)
        {
            _Permissions = GetCheckedPermissions();
            if (_Permissions.Count == 0)
            {

                txtRoleName.MarkInvalid(GetLocalResourceObject("MBNoPermissionsSelected").ToString());
                //FormStatusBar.SetStatus(new StatusBarStatusConfig { Text = GetLocalResourceObject("MBNoPermissionsSelected").ToString(), IconCls = "", Clear2 = true });
                //Ext.Msg.Configure(new MessageBox.Config
                //{
                //    Title =
                //   GetLocalResourceObject("MBErrorCaption").ToString(),
                //    Message = GetLocalResourceObject("MBNoPermissionsSelected").ToString(),
                //    Icon = MessageBox.Icon.ERROR,
                //    Buttons = MessageBox.Button.OK
                //}).Show();
                e.IsValid = false;
            }
        }

        #endregion

        #region [ Functions ]

        /// <summary>
        /// Validates the name of the role.
        /// </summary>
        /// <returns></returns>
        [AjaxMethod]
        public bool ValidateRoleName()
        {
            if (!string.IsNullOrEmpty(txtRoleName.Text))
            {
                bool valid = true;
                if (string.IsNullOrEmpty(EditingRoleID))
                {
                    if (this.ViewModel.DoesRoleNameExist(txtRoleName.Text, null))
                    {
                        valid = false;
                        txtRoleName.MarkInvalid(GetLocalResourceObject("MsgRoleNameIsUsed").ToString());
                    }
                }
                else
                {
                    if (this.ViewModel.DoesRoleNameExist(txtRoleName.Text, EditingRoleID.ToGuid()))
                    {
                        valid = false;
                        txtRoleName.MarkInvalid(GetLocalResourceObject("MsgRoleNameIsUsed").ToString());
                    }
                }
                return valid;
            }
            return true;
        }

        /// <summary>
        /// Gets the checked permissions.
        /// </summary>
        /// <returns></returns>
        private List<Guid> GetCheckedPermissions()
        {
            List<Guid> permissions = new List<Guid>();
            foreach (DataListItem item in lstPermissions.Items)
            {
                Checkbox checkBox = item.FindControl("chkSelect") as Checkbox;
                if (checkBox.Checked)
                {
                    HiddenField hidden = item.FindControl("txtID") as HiddenField;
                    permissions.Add(hidden.Value.ToGuid());
                }
            }
            return permissions;
        }

        /// <summary>
        /// Clears the controls.
        /// </summary>
        private void ClearControls()
        {
            txtRoleName.Reset();
            foreach (DataListItem item in lstPermissions.Items)
            {
                var checkBox = item.FindControl("chkSelect") as Checkbox;
                checkBox.Checked = false;
            }
        }

        #endregion

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "RoleDetails"; }
        }

        #endregion
    }
}
